package com.tucy.logistics.modules.organization.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tucy.logistics.common.base.BaseEnum;
import com.tucy.logistics.common.dto.organization.OrganizationBusinessDto;
import com.tucy.logistics.common.entity.organization.OrganizationBusinessDepartment;
import com.tucy.logistics.common.enums.DepartmentTypeEnum;
import com.tucy.logistics.common.entity.organization.OrganizationBusinessDepartmentRange;
import com.tucy.logistics.modules.organization.mapper.OrganizationBusinessDepartmentRangeMapper;
import com.tucy.logistics.modules.organization.service.OrganizationBusinessDepartmentRangeService;
import com.tucy.logistics.modules.organization.service.OrganizationBusinessDepartmentService;
import com.tucy.logistics.modules.organization.mapper.OrganizationBusinessDepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
* @author tucy123
* @description 针对表【organization_business_department(物流营业部)】的数据库操作Service实现
* @createDate 2023-09-15 16:10:16
*/
@Service
public class OrganizationBusinessDepartmentServiceImpl extends ServiceImpl<OrganizationBusinessDepartmentMapper, OrganizationBusinessDepartment> implements OrganizationBusinessDepartmentService{

    @Autowired
    OrganizationBusinessDepartmentMapper departmentMapper;

    @Autowired
    OrganizationBusinessDepartmentRangeService departmentRangeService;

    @Autowired
    OrganizationBusinessDepartmentRangeMapper departmentRangeMapper;

    /**
     * 增改
     * @param department
     * @return
     */
    @Override
    public Boolean saveOrUpdateBusiness(OrganizationBusinessDepartment department) {
        return this.saveOrUpdate(department);
    }

    /**
     * 查询
     * @return
     */
    @Override
    public List<OrganizationBusinessDepartment> queryBusiness() {
        List<OrganizationBusinessDepartment> departments = this.list();

        return departments.stream().filter(department -> department.getType().equals(DepartmentTypeEnum.TRANSPORT.getValue()))
                .peek(department -> department.setChildren(getChildrenDepartment(department,departments)))
                .collect(Collectors.toList());
    }

    private List<OrganizationBusinessDepartment> getChildrenDepartment(OrganizationBusinessDepartment department, List<OrganizationBusinessDepartment> departments) {
        return departments.stream().filter(transportDepartment -> transportDepartment.getParentId().equals(department.getId()))
                .peek(sortingDepartment -> sortingDepartment.setChildren(getChildrenDepartment(sortingDepartment,departments)))
                .collect(Collectors.toList());
    }

    /**
     * 营业部详情
     * @param id
     * @return
     */
    @Override
    public OrganizationBusinessDepartment queryBusinessDetails(String id) {
        List<OrganizationBusinessDepartmentRange> departmentRanges = departmentRangeService.lambdaQuery().eq(OrganizationBusinessDepartmentRange::getDepartmentId, id).list();

        OrganizationBusinessDepartment organizationBusinessDepartment = departmentMapper.selectById(id);

        if (ObjectUtil.isNotEmpty(departmentRanges)) {
            organizationBusinessDepartment.setPolygon(departmentRanges);
        }

        return organizationBusinessDepartment;
    }

    /**
     * 删除
     * @return
     */
    @Override
    public Boolean deleteBusiness(String id) {
        OrganizationBusinessDepartment businessDepartment = departmentMapper.selectById(id);

        if (businessDepartment.getType().equals(DepartmentTypeEnum.BUSINESS.getValue())) {
            return departmentMapper.deleteById(id) == 1;
        } else if (businessDepartment.getType().equals(DepartmentTypeEnum.SORTING.getValue())) {
            List<OrganizationBusinessDepartment> departmentList = this.lambdaQuery()
                    .eq(OrganizationBusinessDepartment::getParentId, id)
                    .list();
            departmentList.add(businessDepartment);

            return departmentMapper.deleteBatchIds(departmentList) == 1;
        } else {
            List<OrganizationBusinessDepartment> departmentList = this.lambdaQuery()
                    .eq(OrganizationBusinessDepartment::getParentId, id)
                    .list();

            for (OrganizationBusinessDepartment organizationBusinessDepartment : departmentList) {
                departmentList.addAll(this.lambdaQuery().eq(OrganizationBusinessDepartment::getParentId, organizationBusinessDepartment.getId()).list());
            }
            departmentList.add(businessDepartment);

            return departmentMapper.deleteBatchIds(departmentList) != 0;
        }
    }

    /**
     * 查询父类机构
     * @param type
     * @return
     */
    @Override
    public List<OrganizationBusinessDepartment> queryParentBusiness(String type) {
        if (DepartmentTypeEnum.BUSINESS.getValue().equals(Integer.valueOf(type))) {
            return this.lambdaQuery().eq(OrganizationBusinessDepartment::getType,DepartmentTypeEnum.SORTING.getValue()).list();
        } else if (DepartmentTypeEnum.SORTING.getValue().equals(Integer.valueOf(type))) {
            return this.lambdaQuery().eq(OrganizationBusinessDepartment::getType,DepartmentTypeEnum.TRANSPORT.getValue()).list();
        } else {
            return null;
        }
    }

    /**
     * 增改机构范围
     * @param department
     * @return
     */
    @Override
    public Boolean saveUpdateBusinessRange(OrganizationBusinessDepartment department) {
        //机构系统编号
        Long departmentId = department.getId();
        //机构范围坐标
        List<OrganizationBusinessDepartmentRange> polygon = department.getPolygon();

        //删除原本范围
        List<OrganizationBusinessDepartmentRange> ranges = departmentRangeService.lambdaQuery().eq(OrganizationBusinessDepartmentRange::getDepartmentId, departmentId).list();
        if (ObjectUtil.isNotEmpty(ranges)) {
            departmentRangeMapper.deleteBatchIds(ranges);
        }

        polygon.forEach(range -> range.setDepartmentId(departmentId));
        return departmentRangeService.saveOrUpdateBatch(polygon);
    }

    /**
     * 删除机构范围
     * @param id
     * @return
     */
    @Override
    public Boolean deleteBusinessRange(String id) {
        List<OrganizationBusinessDepartmentRange> ranges = departmentRangeService.lambdaQuery()
                .eq(OrganizationBusinessDepartmentRange::getDepartmentId, id).list();
        return departmentRangeMapper.deleteBatchIds(ranges) != 0;
    }

    /**
     * 导出营业机构
     * @return
     */
    @Override
    public void exportBusiness(HttpServletResponse response) throws Exception {
        List<OrganizationBusinessDepartment> businessDepartments = this.list();
        List<OrganizationBusinessDto> businessDtoList = BeanUtil.copyToList(businessDepartments, OrganizationBusinessDto.class);
        //不是最高大区的运营机构
        List<OrganizationBusinessDto> businessList = businessDtoList.stream()
                .filter(b -> !b.getParentId().equals(BaseEnum.NORMAL.getValue().toString())).collect(Collectors.toList());
        businessList.forEach(business -> {
            OrganizationBusinessDto department = businessDtoList.stream()
                    .filter(b -> business.getParentId().equals(b.getId())).findFirst().get();
            business.setParentId(department.getName());
            business.setType(DepartmentTypeEnum.getByValue(Integer.valueOf(business.getType())).getKey());
        });

        //最高大区处理
        businessDtoList.forEach(business -> {
            if (business.getParentId().equals(BaseEnum.NORMAL.getValue().toString())) {
                business.setParentId("最高大区");
                business.setType(DepartmentTypeEnum.getByValue(Integer.valueOf(business.getType())).getKey());
            }
        });

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("运营机构表-" + DateUtil.formatDate(new Date()) + ".xlsx", "UTF-8"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        try {
            EasyExcel.write(response.getOutputStream(), OrganizationBusinessDto.class).sheet("导出数据").doWrite(businessDtoList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}




